﻿using System;
using System.Reflection;
using System.Windows;
using ControleRepresentanteSync.Application.Wizard;
using Microsoft.Win32;

namespace ControleRepresentanteSync.Application.Setup
{
    internal class StartupPagePresenter : WizardPagePresenterBase<IStartupPageViewModel>
    {
        private readonly IUserInterfaceService _UserInterfaceService;
        private const string RegistryRunKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
        private const string RegistryKey = "ControleRepresentanteSync";

        public StartupPagePresenter(IStartupPageViewModel viewModel, bool isFirstTime, IUserInterfaceService userInterfaceService)
            : base(viewModel)
        {
            _UserInterfaceService = userInterfaceService;
            if (isFirstTime)
            {
                ViewModel.IsRunOnStartup = true;
            }
            else
            {
                RegistryKey runSubKey = Registry.LocalMachine.OpenSubKey(RegistryRunKey, RegistryKeyPermissionCheck.ReadSubTree);
                ViewModel.IsRunOnStartup = ((string)runSubKey.GetValue(RegistryKey)) != null;
            }
            ViewModel.IsValid = true;
        }

        protected override bool TryApply()
        {
            try
            {
                RegistryKey runSubKey = Registry.LocalMachine.OpenSubKey(RegistryRunKey,
                    RegistryKeyPermissionCheck.ReadWriteSubTree);

                bool exists = ((string) runSubKey.GetValue(RegistryKey)) != null;

                if (ViewModel.IsRunOnStartup)
                {
                    if (!exists)
                    {
                        runSubKey.SetValue(RegistryKey, Assembly.GetExecutingAssembly().Location);
                    }
                }
                else
                {
                    if (exists)
                    {
                        runSubKey.DeleteValue(RegistryKey);
                    }
                }

                return true;
            }
            catch (Exception exception)
            {
                _UserInterfaceService.ShowMessage(exception.Message, "Erro configurando inicialização", MessageBoxButton.OK, MessageBoxImage.Error);
                return true;
            }
        }
    }
}